package com.financing.wap.web.controller.api;

import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.wap.common.ResultMap;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.dto.FpHdFinancingBlindDTO;
import com.financing.wap.dto.RegisterDTO;
import com.financing.wap.service.ICheckCodeService;
import com.financing.wap.service.IFpHdFinancingBlindService;
import com.financing.wap.service.IRegisterService;
import com.financing.wap.service.ISmsService;
import com.financing.wap.service.IUserService;
import com.financing.wap.util.DTOdateSetUtil;
import com.financing.wap.util.DateUtil;
import com.financing.wap.util.PropertiesUtils;
import com.financing.wap.util.RandomUtils;
import com.financing.wap.util.StringUtil;
import com.financing.wap.web.controller.BaseController;

@Controller("fpHdFinancingBlindController")
@RequestMapping("/api/activity")
public class FpHdFinancingBlindController extends BaseController  { 

	private Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private IFpHdFinancingBlindService fpHdFinancingBlindService;
	
	@Autowired
	private ICheckCodeService checkCodeServiceImpl;//判断短信服务
	
	@Autowired
	private IUserService userService;//用户服务
	
	@Autowired
	private IRegisterService registerService;//注册服务
	
	
	@RequestMapping("/financingBlind")
	@ResponseBody
	public synchronized ResultMap add(HttpServletRequest request, FpHdFinancingBlindDTO fpHdFinancingBlind){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("add fpHdFinancingBlind  begin .......");
			
			String mobile = fpHdFinancingBlind.getMobile();
			String vCode =  fpHdFinancingBlind.getvCode();
			
			//判断参数缺失
			if(StringUtil.isNullOrEmptyNStr(mobile,vCode)){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				return result;
			}
			
			//判断用户是否存在
			FpHdFinancingBlindDTO resultBean = fpHdFinancingBlindService.loadByMobile(fpHdFinancingBlind.getMobile());
			if(resultBean != null){
				//已经被注册
				result.setStatus(ResultMap.STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_2022);
				return result;
			}

			
			//判断验证码是否正确
			Integer activety_otp_time= new Integer(PropertiesUtils.getValue("activety_otp_time")); 
			logger.info("start check OTP~");
			logger.info("activity time is "+activety_otp_time+" m");
			if(checkCodeServiceImpl.CheckCodeSwitch() && checkOtpCodeTimeOut_(mobile,activety_otp_time,ISmsService.OTP_CODE_FIRST_TIME)){//验证短息30分钟内有效
				result.setStatus(ResultMap.STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_OTP_VALIDATE_ERROR_TIMEOUT);
				result.setMessage("手机验证码超时！");
				return result;
			}

			if(checkCodeServiceImpl.CheckCodeSwitch() && !vCode.equalsIgnoreCase(getOtpCode(mobile))){//验证码校验
				log.info("error otpcode");
				//校验验证码--未通过
				result.setStatus(ResultMap.STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_OTP_VALIDATE_ERROR);
				result.setMessage("手机验证码不正确！");
				return result;
			}
			
			
			//自动注册理财师
			if(!userService.isMobileRegistered(mobile)){
				//未注册注册
				RegisterDTO register = new RegisterDTO();
				register.setActSource(fpHdFinancingBlind.getActCode());
				register.setMobile(mobile);
				String pwd="sfa"+RandomUtils.getRandomUtils(6);
				System.out.println(mobile+":"+pwd);
				register.setPassword(pwd);
				registerService.doRegister(register);
				
			}
			
			//新增金融相亲信息
			DTOdateSetUtil.setCreateInfo(fpHdFinancingBlind);
			DTOdateSetUtil.setUpdateInfo(fpHdFinancingBlind);
			fpHdFinancingBlind.setIsJoinWechat("0");//默认 0  否加入群
			fpHdFinancingBlind.setDeleteTag("1");
			fpHdFinancingBlind.setUserStatus("01");//用户状态  01正常，02 活跃，03警告，04 拉黑
			fpHdFinancingBlind.setBirthday(DateUtil.getStringTZ(fpHdFinancingBlind.getBirthday()));
			String wxOpenid="";
			try {
				wxOpenid = (String) getSession(true).getAttribute(WeixinController.OPENID);
				logger.info("getSession(true).getAttribute(ccc):"+wxOpenid);
			} catch (Exception e) {
				logger.error("getSession(true).getAttribute(ccc):",e);
			}

			fpHdFinancingBlind.setOpenid(wxOpenid);
			int id = fpHdFinancingBlindService.insert(fpHdFinancingBlind);
			
			
			result.setAttribute("id", id);
			
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("add fpHdFinancingBlind list end .......");
		}catch(Exception e){
			log.error("add fpHdFinancingBlind error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	/**
	 * 进行验证码超时验证
	 * @param mobile 手机号
	 * @param time 分钟数
	 * @return true:超时，false:未超时
	 */
	protected boolean checkOtpCodeTimeOut_(String mobile,int time,String timeOutType){
		log.info("begin get opt code time");
		Date otpCodeDateTime = getOtpCodeTime(mobile,timeOutType);
		log.info("begin get opt code time end"+otpCodeDateTime);
		if(otpCodeDateTime==null){
			log.info("==first otpDateTime is null==");
			return false;
		}
		Calendar otpCodeCa = Calendar.getInstance();
		//otp时间
		otpCodeCa.setTime(otpCodeDateTime);
		otpCodeCa.add(Calendar.MINUTE, time);
		Calendar ca= Calendar.getInstance();
		//当前比较时间
		ca.setTime(new Date());
		
		return otpCodeCa.before(ca);
	}
	
	
}
